/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.provider.custom;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.asiainfo.ability.base.code.Constants;
import org.asiainfo.ability.base.code.InstanceState;
import org.asiainfo.ability.base.queue.OperHandler;
import org.asiainfo.ability.base.queue.QueueObserver;
import org.asiainfo.ability.base.queue.support.RouteServerEvent;
import org.asiainfo.ability.base.utils.ExceptionUtils;
import org.asiainfo.ability.base.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;

/**
 * @Author: visen
 * @Date: 2018/1/19
 * @Description:
 */
public class CustomZoneAvoidanceRule extends ZoneAvoidanceRule {
    public static final Logger logger = LogManager.getLogger(CustomZoneAvoidanceRule.class);
    @Autowired
    EurekaClient eurekaClient;
    @Autowired
    QueueObserver queueObserver;

    private static final String BRANCH = "branch";
    private static final String WEIGHT = "weight";
    private static final String IS_SILENT = "isSilent";
    private Map<String, List<Server>> transientServers;
    private LoadBalancerClient loadBalancerClient;
    private boolean isRelease = false;
    private final static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private Function<Object, Server> function;

    public CustomZoneAvoidanceRule() {
        super();
    }

    public CustomZoneAvoidanceRule(boolean isRelease, LoadBalancerClient loadBalancerClient) {

        super();
        this.loadBalancerClient = loadBalancerClient;
        this.isRelease = isRelease;

    }

    @PostConstruct
    public void init() {
        transientServers = new HashMap<>();
        queueObserver.subscribeEvent(RouteServerEvent.class, new OperHandler<RouteServerEvent>() {
            @Override
            public void process(RouteServerEvent event) {
                InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder();
                builder.setIPAddr(event.getIp());
                builder.setPort(event.getPort());
                builder.setHostName(event.getIp());
                builder.setAppName(event.getIp() + event.getPort());
                InstanceInfo instanceInfo = builder.build();
                if (!StringUtils.isBlank(event.getBranch())) {
                    instanceInfo.getMetadata().put(BRANCH, event.getBranch());
                }
                if (event.getState() == InstanceState.pause) {
                    instanceInfo.getMetadata().put(Constants.IS_PAUSED, "1");
                }
                Server server = new DiscoveryEnabledServer(instanceInfo, false);
                server.setAlive(event.getState() == InstanceState.active
                        || event.getState() == InstanceState.pause);

                addTransientServer(event.getServiceName(), server);
            }
        });
    }

    public void addTransientServer(String serviceName, Server server) {
        lock.writeLock().lock();
        try {
            List serviceServers = transientServers.get(serviceName);
            if (serviceServers == null) {
                serviceServers = new ArrayList();
                transientServers.put(serviceName, serviceServers);
            }

            int i = serviceServers.indexOf(server);
            if (i > -1) {
                serviceServers.remove(i);
            }
            serviceServers.add(server);

        } catch (Exception e) {
            ExceptionUtils.logTrace(logger, e);
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void removeTransientServer(String serviceName, int index) {
        lock.writeLock().lock();
        try {
            List serviceServers = transientServers.get(serviceName);
            if (serviceServers != null) {
                serviceServers.remove(index);
            }
            if (serviceServers.isEmpty()) {
                transientServers.remove(serviceName);
            }
        } catch (Exception e) {
            ExceptionUtils.logTrace(logger, e);
        } finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * fix eureka , immediately discovery the instance
     *
     * @param key
     * @return
     */
    //@Override
    public Server choose(Object key) {

        ILoadBalancer lb = getLoadBalancer();
        List<Server> allServers = lb.getAllServers();

        if (!transientServers.isEmpty()) {

            List<Server> tempTransientServers = new ArrayList<>();
            String serviceName = ((DynamicServerListLoadBalancer) lb).getName();
            try {
                lock.readLock().lock();
                List<Server> serviceServers = transientServers.get(serviceName);
                if (serviceServers != null) {
                    tempTransientServers.addAll(serviceServers);
                }
            } catch (Exception e) {
                ExceptionUtils.logTrace(logger, e);
            } finally {
                lock.readLock().unlock();
            }
            if (!tempTransientServers.isEmpty()) {
                allServers = new ArrayList<>(allServers);
                for (int i = 0, len = tempTransientServers.size(); i < len; i++) {
                    Server server = tempTransientServers.get(i);
                    if (!server.isAlive()) {
                        if (!allServers.remove(server)) {
                            removeTransientServer(serviceName, i);
                        }
                    } else {
                        int j = allServers.indexOf(server);
                        if (j == -1) {
                            allServers.add(server);
                        } else {
                            Map<String, String> metaData = ((DiscoveryEnabledServer) server).getInstanceInfo()
                                    .getMetadata();

                            if ("1".equals(metaData.get(Constants.IS_PAUSED))) {
                                metaData = ((DiscoveryEnabledServer) allServers.get(j)).getInstanceInfo()
                                        .getMetadata();
                                if ("1".equals(metaData.get(Constants.IS_PAUSED))) {
                                    removeTransientServer(serviceName, i);
                                } else {
                                    metaData.put(Constants.IS_PAUSED, "1");
                                }
                            } else {
                                metaData = ((DiscoveryEnabledServer) allServers.get(j)).getInstanceInfo()
                                        .getMetadata();
                                if ("1".equals(metaData.get(Constants.IS_PAUSED))) {
                                    metaData.put(Constants.IS_PAUSED, "0");
                                } else {
                                    removeTransientServer(serviceName, i);
                                }

                            }


                        }
                    }
                }
            }


        }
        RequestContext requestContext = RequestContext.getCurrentContext();

        boolean isSilent = requestContext.containsKey(IS_SILENT) ? (Boolean) requestContext.get(IS_SILENT)
                : false;

        if (allServers.isEmpty()) return null;
        String branch = (String) RequestContext.getCurrentContext().get("branch");
        List<Server> filterServers = new ArrayList<>();
        Map<String, Integer> weights = new HashMap<>();

        int sumWeight = -1;
        boolean linear = true;
        for (Server server : allServers) {
            Map<String, String> metaData = ((DiscoveryEnabledServer) server).getInstanceInfo().getMetadata();
            if (StringUtils.isBlank(branch)) {
                String branchValue = metaData.get(BRANCH);
                if (!StringUtils.isBlank(branchValue) && !"master".equals(branchValue)) {
                    continue;
                }
            } else if (!branch.equals(metaData.get(BRANCH))) {
                continue;
            }
            if (!isSilent ? !"1".equals(metaData.get(Constants.IS_PAUSED))
                    : "1".equals(metaData.get(Constants.IS_PAUSED))) {
                filterServers.add(server);
                int weight = metaData.containsKey(WEIGHT) ? new Integer(metaData.get(WEIGHT)) : 1;
                if (sumWeight == -1) {
                    sumWeight = weight;
                } else {
                    if (linear && sumWeight != weight) {
                        linear = false;
                    }
                }
                weights.put(server.getId(), weight);
            }
        }

        List<Server> eligible = getPredicate().getEligibleServers(filterServers, key);
        if (eligible.size() == 0) {
            return null;
        }
        sumWeight = 0;
        Server selServer = null;
        if (linear) {
            selServer = eligible.get(ThreadLocalRandom.current().nextInt(eligible.size()));
        } else {
            for (Server server : eligible) {
                sumWeight += weights.get(server.getId());
            }
            int curSeed = ThreadLocalRandom.current().nextInt(sumWeight);

            for (int i = eligible.size() - 1; i >= 0; i--) {
                //sumWeight
                selServer = eligible.get(i);
                sumWeight -= weights.get(selServer.getId());
                if (sumWeight <= curSeed) {
                    break;
                }
            }
        }

        /*
        AbilityRequestContext abilityRequestContext = (AbilityRequestContext) RequestContext
                .getCurrentContext().get(AbilityRequestContext.CONTEXT_KEY);
        if (abilityRequestContext != null) {
            abilityRequestContext.getRecord().setInstanceId(selServer.getId());
        }
        */
        return selServer;

    }


}
